package com.firemoss.atonement.frameworks.magicbus
{
	import com.firemoss.atonement.entitymanager.EntityManager;
	import com.firemoss.atonement.entitymanager.util.IdUtil;
	import com.firemoss.atonement.mapper.Mapper;
	
	import mx.collections.IList;

	public class EntityAssembler extends MappingAssembler
	{
		public var entityManager : EntityManager

		public function EntityAssembler( entityManager : EntityManager = null, mapper : Mapper = null, entityClass : Class = null, dtoClass : Class = null ) 
		{
			this.mapper = mapper
			this.entityClass = entityClass
			this.dtoClass = dtoClass
			this.entityManager = entityManager
		}
		
		override public function assemble(source:*, target:*=null):Object
		{
			if ( source is Array || source is IList )
			{
				return super.assemble( source, target );
			}
			else
			{
				var id : * = IdUtil.getIdValue( source, entityManager, entityClass )
					
				if ( id != null )
				{
					target = entityManager.get( entityClass, id )
				}				
				var result : Object = super.assemble( source, target )
				
				entityManager.put( result )
				
				return result;
			}
		}
		
		
	}
}